import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar -- 导入进度条组件
import 'nprogress/nprogress.css' // progress bar style -- 导入进度条样式
import { getToken } from '@/utils/auth' // get token from cookie -- 从cookie中获取token
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration 进度条配置

const whiteList = ['/login', '/register'] // no redirect whitelist -- 不重定向白名单
// 全局权限路由守卫
router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in -- 确认用户是否已经登陆成功
  const hasToken = getToken()
  console.log(hasToken)
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page -- 如果已经登入了，直接跳转到首页
      next({ path: '/' })
      NProgress.done()
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      // 确认用户信息中的角色是否拥有权限
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          // 获取用户信息，角色信息必须是一个对象数组，例如 ['admin'] or ,['developer','editor']
          // const { roles } = await store.dispatch('user/getInfo')
          const { rolesArrays, rolseCodeArrays } = await store.dispatch('user/getUserRolesInfo')
          console.log(rolesArrays)
          // generate accessible routes map based on roles
          // 基于角色数组生成可访问的角色集合
          const accessRoutes = await store.dispatch('permission/generateRoutes', rolseCodeArrays)
          console.log(accessRoutes)
          // dynamically add accessible routes
          // 动态增加可访问路由
          router.addRoutes(accessRoutes)

          // hack method to ensure that addRoutes is complete
          // 确保增加角色完成
          // set the replace: true, so the navigation will not leave a history record
          // 设置replace:true，这样导航就不会留下历史记录
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          // 移除token，回到登录页面重新登陆
          await store.dispatch('user/resetToken') // 清空token
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`) // 跳到登陆界面
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token -- 没有携带token*/
    if (whiteList.indexOf(to.path) !== -1) {
      console.log(whiteList.indexOf(to.path))
      console.log('没有token 且在白名单的情况')
      // in the free login whitelist, go directly 在免登录白名单里，重定向到该页面
      next()
    } else {
      console.log('没有token 不在白名单的情况')
      // other pages that do not have permission to access are redirected to the login page.
      // 那些需要对应权限访问的页面，直接重定向到登陆页面
      next(`/login?redirect=${to.path}`)
      NProgress.done()// finish progress bar -- 完成进度条
    }
  }
})

router.afterEach(() => {
  // finish progress bar -- 完成进度条
  NProgress.done()
})
